<?php

class CheckAuctionController extends Admin_Controller {

    const NO_ERRORS = 0x00;
    const ERROR_FILE_TYPE = 0x01;
    const ERROR_EXCHANGE_FILE = 0x02;
    const UPLOAD_ERROR = 0x03;
    const DB_ERROR = 0x04;

    public function init() {
        parent::init();
        $this->setActiveCat(987);
        $this->_table = new Admin_Table_Auction_Auction();
        $this->_table_lots = new Admin_Table_Auction_Lots();
    }

    public function indexAction() {

        $form = new Llib_Form($this->_request);
        $filters = array();

        if ($this->_request->isPost()) {
            $filters['by_date'] = $this->_request->getParam('by_date', '');
            $filters['from_date'] = $this->_request->getParam('from_date', '');
            $filters['to_date'] = $this->_request->getParam('to_date', '');
            $filters['by_region'] = $this->_getParam('by_region', '');
            $filters['by_district'] = $this->_getParam('by_district', '');
            $filters['by_town'] = $this->_getParam('by_town', '');
            $filters['by_status'] = $this->_request->getParam('by_status', '');
        }

        $filters = $this->SessionVarsEx($filters, array('by_date', 'from_date', 'to_date', 'by_region' => 0, 'by_district' => 0, 'by_town' => 0, 'by_status' => 0), $this->_request->getParam('reset', false));

        $id_region = $filters['by_region'];
        $id_district = $filters['by_district'];
        $id_town = $filters['by_town'];

        $filters['id_region'] = $this->_table->addressGetRegions($id_region);
        $filters['id_district'] = $this->_table->addressGetDistricts($id_region, $id_district);
        $filters['id_town'] = $this->_table->addressGetTowns($id_region, $id_district, $id_town);
        $filters['id_status'] = $this->_table_lots->GetStatusList($filters['by_status']);
        array_splice($filters['id_status'], 3);
        if (isset($this->_user->koatuu) && $this->_user->koatuu != 0)
            $filters['koatuu'] = $this->_user->koatuu;

        $form->AddData($filters);

        $lclm = new Llib_List($this->_request, $this->_sess);
        /* $lclm->AddParams(array(
          'checkboxes' => true,
          'link_fields'=>array('start_date'),
          'link' => "/" . $this->controller . "/view/"//"/lots/"
          )); */
        $lclm->AddColumn('№ Аукціону', 'id', array('width' => '10%', 'sort' => 1));
        $lclm->AddColumn('Дата проведення', 'start_date', array('width' => '15%', 'sort' => 1));
        $lclm->AddColumn('Область', 'region', array('width' => '20%', 'sort' => 1));
        $lclm->AddColumn('Район', 'district', array('width' => '20%', 'sort' => 1));
        $lclm->AddColumn('Населений пункт', 'town', array('width' => '20%', 'sort' => 1));
        $lclm->AddColumn('Статус', 'status', array('width' => '15%', 'sort' => 1));
        $lclm->AddColumn('', 'is_published', array('width' => '1%', 'sort' => 1));
        $lclm->AddData($this->_table->getDataList($lclm->page, $lclm->s, $lclm->pager_count, $filters));


        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->assign('List', $lclm->GetList());
        $this->view->assign($form->GetFrom());
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }

    public function editAction() {
        $id = intval($this->_request->getParam('id'));
        if (empty($id))
            $this->_redirect('/error/e404');
        $this->_redirect('/' . $this->controller . '/view/' . $id);
    }

    public function viewAction() {
        $id = $this->_request->getParam('id');

        if (!($id > 0))
            $this->_redirect('/error/e404');

        $form = new Llib_Form($this->_request);

        if ($this->_request->isPost()) {
            $posted_data = $form->GetPostedData();
            if (!empty($posted_data)) {
                if (isset($posted_data['id_status'])) {
                    unset($posted_data['id']);
                    // count of lots in this auction
                    $c = $this->_table->getAuctionLotsCount($id);
                    //count of published lots in this auction
                    $pc = $this->_table->getAuctionLotsCount($id, true);
                    // all lots must be checked
                    if ($c['lots_count'] == $pc['lots_count']) {
                        if ($this->_table->update($posted_data, $id, $this->_user->id, $this->_user->role_id)) {
                            $form->SetSuccess("Статус успішно змінено.");
                        }else
                            $form->SetError("Ви не можете опубліковати матеріал у зв'язку з тим, що його було відкликано з перевірки");
                    }else
                        $form->SetError("Ви не можете опубліковати аукціон у зв'язку з тим, що не всі його лоти ще перевірені");
                }else
                    $form->SetError("Ви не змінили статус.");
            }
        }

        $data = $this->_table->getAuctionInfo($id);
        $data = array_merge($data, $this->_table->getAuctionLotsCount($id));
        $idstatus = intval(@$data['id_status']);
        //первый параметр устанавливает оператора для выборки списка возможных статусов
        $data['status_list'] = $this->_table->GetStatusListForChange(1, @$data['id_status']);
        array_splice($data['status_list'], 3);

        $form->AddData($data);

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->xmlWriter->writeAttribute('id', $id);
        $this->view->assign($form->GetFrom());
        //!!!!!!!!!!!!!!!!!!!!!!
        //Понадобится после определения списка причин для возвращения 
        //changed: CheckAuctionController.php, auction_change_stat.js, view.xls, db_auction_lots(added column:rejectReason)
        //!!!!!!!!!!!!!!!!!!!!!!
        //--------------------------------
        //if($idstatus==1) $this->view->assign('rejectReason',$this->_table_lots->getStatusReasons());
        //--------------------------------
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }

    public function auctionHistoryAction() {
        $id = $this->_request->getParam('id', 0);

        if (!($id > 0))
            $this->_redirect('/error/e404');

        $table_history = new Admin_Table_Auction_LotHistory();

        $lclm = new Llib_List($this->_request, $this->_sess);
        $lclm->AddParams(array(
            'checkboxes' => false,
            'link_fields' => array('file_name'),
            'link' => "/" . $this->controller . "/lot-history/" . $id . "/"
        ));
        $lclm->AddColumn('Дата', 'add_date', array('width' => '5%', 'sort' => 1));
        $lclm->AddColumn('Користувач', 'user', array('width' => '20%', 'sort' => 0));
        $lclm->AddColumn('Коментар', 'comment', array('width' => '20%', 'sort' => 0));
        $lclm->AddColumn('На статус', 'status', array('width' => '20%', 'sort' => 0));
        $lclm->AddColumn('З причиною', 'reason', array('width' => '35%', 'sort' => 0));
        $lclm->AddData($table_history->getDataList($lclm->page, $lclm->s, $lclm->pager_count, array('id_lot' => '0', 'id_auction' => $id)));

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->xmlWriter->writeAttribute('id', $id);
        $this->view->assign('List', $lclm->GetList());
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }

    public function lotsAction() {
        $id = $this->_request->getParam('id');
        if ($id == 0)
            $this->_redirect('/auction-lots');
        if (!($id > 0))
            $this->_redirect('/error/e404');

        $filters = array();

        if ($this->_request->isPost()) {
            $filters['by_cad_num'] = $this->_request->getParam('by_cad_num', '');
            $filters['by_approved'] = $this->_request->getParam('by_approved', '');
            $filters['by_gone'] = $this->_request->getParam('by_gone', '');
        }

        $filters = $this->SessionVarsEx($filters, array('by_cad_num', 'by_approved' => '-1', 'by_gone' => '-1'), $this->_request->getParam('reset', false));
        $error = intval($this->_request->getParam('error'));

        $form = new Llib_Form($this->_request);

        if ($error) {
            switch ($error) {
                case AuctionController::ERROR_EXCHANGE_FILE:
                    $form->SetError("Обмінний файл містить помилки.");
                    break;
                case AuctionController::ERROR_FILE_TYPE:
                    $form->SetError("Не вірний формат файлу.");
                    break;
                case AuctionController::UPLOAD_ERROR:
                    $form->SetError("Виникла помилка під час завантаження обмінного файлу.");
                    break;
                case AuctionController::DB_ERROR:
                    $form->SetError("Не вдалося створити лот. Виникла помилка бази даних.");
                    break;
                default:
                    $form->SetError("Виникла помилка під час створення лоту.");
                    break;
            }
        }
        $filters = array_merge($filters, $this->_table->getAuctionLotsCount($id));
        $filters['is_approved'] = $this->_table_lots->GetApprovedList($filters['by_approved']);
        $filters['is_gone'] = $this->_table_lots->GetGoneList($filters['by_gone']);

        $filters['id_auction'] = $id;
        if (isset($this->_user->koatuu) && $this->_user->koatuu != 0)
            $filters['koatuu'] = $this->_user->koatuu;

        $lclm = new Llib_List($this->_request, $this->_sess);
        $lclm->AddParams(array(
            'checkboxes' => true,
            'link_fields' => array('cad_num'),
            'link' => "/auction-lots/" // . "/id-lot/"//"/file-attache/" . $id . "/id-lot/"
        ));
        $lclm->AddColumn('№ Лоту', 'id', array('width' => '5%', 'sort' => 1));
        $lclm->AddColumn('Кадастровий номер', 'cad_num', array('width' => '10%', 'sort' => 1));
        $lclm->AddColumn('Площа (га)', 'area', array('width' => '5%', 'sort' => 1));
        $lclm->AddColumn('Адреса', 'parcel_address', array('width' => '30%', 'sort' => 1));
        $lclm->AddColumn('Цільове призначення', 'purpose', array('width' => '30%', 'sort' => 0));
        $lclm->AddColumn('', 'attantion', array('width' => '1%', 'sort' => 0));
        $lclm->AddColumn('Статус', 'status', array('width' => '20%', 'sort' => 1));
        $lclm->AddColumn('', 'is_published', array('width' => '1%', 'sort' => 1));
        $lclm->AddData($this->_table_lots->getDataList(/* $id, */$lclm->page, $lclm->s, $lclm->pager_count, $filters));
        $form->AddData($filters);

        $this->startContent();
        $this->view->xmlWriter->startElement("Main");
        $this->view->xmlWriter->writeAttribute('id', $id);
        $this->view->assign('List', $lclm->GetList());
        $this->view->assign($form->GetFrom());
        $this->view->xmlWriter->endElement();
        $this->view->xmlWriter->endElement();
    }

    /*
      public function lotHistoryAction() {
      $id = $this->_request->getParam('id',0);
      if (!($id>0)) $this->_redirect('/error/e404');

      $table_history = new Admin_Table_Auction_LotHistory();

      $lclm = new Llib_List($this->_request, $this->_sess);
      $lclm->AddParams(array(
      'checkboxes' => false,
      'link_fields'=>array('file_name'),
      'link' => "/" . $this->controller . "/lot-history/" . $id . "/"
      ));
      $lclm->AddColumn('Дата', 'add_date', array('width' => '5%', 'sort' => 1));
      $lclm->AddColumn('Користувач', 'user', array('width' => '20%', 'sort' => 0));
      $lclm->AddColumn('Коментар', 'comment', array('width' => '20%', 'sort' => 0));
      $lclm->AddColumn('На статус', 'status', array('width' => '20%', 'sort' => 0));
      $lclm->AddColumn('З причиною', 'reason', array('width' => '35%', 'sort' => 0));
      $lclm->AddData($table_history->getDataList($lclm->page, $lclm->s, $lclm->pager_count, array('id_lot'=>$id)));

      $this->startContent();
      $this->view->xmlWriter->startElement("Main");
      $this->view->xmlWriter->writeAttribute('id', $id);
      $this->view->assign('List', $lclm->GetList());
      $this->view->xmlWriter->endElement();
      $this->view->xmlWriter->endElement();
      }

      private function getDataFromLotXML($id){
      $dataFromXML = array('id_lot'=>$id);
      $table_exchange_files = new Admin_Table_Auction_ExchangeFile();
      $info = $table_exchange_files->GetDataRow(array('id_lot'=>$id));

      if(!empty($info)){
      $dataFromXML['id_exchange']=$info['ID'];

      $xml = new Llib_Xml($info['FILE_PATH'].'/'.$info['FILE_NAME']);
      $parcel_info = $xml->getParcelInfo();

      $dataFromXML['category'] = intval($parcel_info['CategoryPurposeInfo']['Category']);
      $dataFromXML['use'] = trim($parcel_info['CategoryPurposeInfo']['Use']);
      $dataFromXML['ownership_code'] = intval($parcel_info['OwnershipInfo']);
      $dataFromXML['area_measurement'] = trim($parcel_info['ParcelMetricInfo']['Area']['MeasurementUnit']);

      $coordinat_info = $xml->getMetricInfo();
      $dataFromXML['coordsys_code'] = 0;

      if (!empty($coordinat_info) && isset($coordinat_info['CoordinateSystem'])){
      switch ($coordinat_info['CoordinateSystem']) {
      case 'SC63':
      $dataFromXML['coordsys_code'] = 10630;
      break;
      case 'SC42':
      $dataFromXML['coordsys_code'] = 10426;
      break;
      case 'SC42_3':
      $dataFromXML['coordsys_code'] = 10423;
      break;
      }
      if ($dataFromXML['coordsys_code']>0){
      if(isset($coordinat_info['CoordinateSystemZone'])) $dataFromXML['coordsys_code'] .= intval($coordinat_info['CoordinateSystemZone']);
      else $dataFromXML['coordsys_code'] .= 0;

      $PPoint = "";
      $xml = $xml->getSimpleXmlObj();
      $MetricInfo = $xml->InfoPart->MetricInfo;
      $ParcelsNode = $xml->InfoPart->CadastralZoneInfo->CadastralQuarters->CadastralQuarterInfo->Parcels->ParcelInfo;

      $Node = $MetricInfo->PointInfo->Point;
      if(sizeof($Node)>0){
      $Points = Array();
      foreach ($Node as $PointInfo) {
      $Points[(string)$PointInfo->UIDP] = array('X'=>(string)$PointInfo->X, 'Y'=>(string)$PointInfo->Y);
      }

      if(!empty($Points)){
      $Node = $MetricInfo->Polyline->PL;
      if(sizeof($Node)>0){
      $PL = Array();
      foreach ($Node as $PolylineInfo) {
      $PL[(string)@$PolylineInfo->ULID] = array();
      $P = @$PolylineInfo->Points->P;
      if(isset($P) && !empty($P)){
      foreach ($P as $v) {
      $PL[(string)@$PolylineInfo->ULID][] = (string)$v;
      }
      }
      }

      if(!empty($PL) && !empty($ParcelsNode) && is_object($ParcelsNode)){
      $LineNode = @$ParcelsNode->ParcelMetricInfo->Externals->Boundary->Lines->Line;
      if(sizeof($LineNode)>0){
      $PoligonPoints = Array();
      $i = 0;
      foreach ($LineNode as $LineTurn) {
      foreach ($PL[(int)$LineTurn->ULID] as $v) {
      $PoligonPoints[$i] = $Points[$v];
      if($PPoint!="") $PPoint .= ",";
      $PPoint .= (float) str_ireplace(",",".",$Points[$v]['X'])." ".(float) str_ireplace(",",".",$Points[$v]['Y']);
      $i++;
      }
      }
      }
      }
      }
      }
      }



      if($PPoint!=""){
      $endPoint = end($PoligonPoints);
      if (!($PoligonPoints[0]['X']==$endPoint['X'] && $PoligonPoints[0]['Y']==$endPoint['Y'])) $PPoint .= ",".(float) str_ireplace(",",".",$PoligonPoints[0]['X'])." ".(float) str_ireplace(",",".",$PoligonPoints[0]['Y']);
      }
      unset($xml);
      $dataFromXML['the_geom']=$PPoint;
      }
      }
      }
      return $dataFromXML;
      }

      public function fileAttacheAction() {
      $id = intval($this->_request->getParam('id'));
      if (empty($id)) $this->_redirect('/error/e404');

      $filters = array();

      if ($this->_request->isPost()) $filters['by_file_type'] = $this->_request->getParam('by_file_type', '');

      $filters = $this->SessionVarsEx($filters, array('by_file_type'), $this->_request->getParam('reset', false));

      $table_attaches = new Admin_Table_Auction_Attaches();
      $form = new Llib_Form($this->_request);
      $data['attache_types'] = $table_attaches->getFileTypes();
      $data = array_merge($data, $table_attaches->getLotFilesCount($id));
      $data = array_merge($data, $filters);
      $form->AddData($data);

      $lclm = new Llib_List($this->_request, $this->_sess);
      $lclm->AddParams(array(
      'checkboxes' => false,
      'link_fields'=>array('file_name'),
      'link' => "/" . $this->controller . "/download/" . $id . "/attache/"
      ));
      $lclm->AddColumn('Імя файлу', 'file_name', array('width' => '30%', 'sort' => 1));
      $lclm->AddColumn('Тип файлу', 'file_type', array('width' => '70%', 'sort' => 1));
      $lclm->AddData($table_attaches->getDataList($id, $lclm->page, $lclm->s, $lclm->pager_count, $filters));

      $this->startContent();
      $this->view->xmlWriter->startElement("Main");
      $this->view->xmlWriter->writeAttribute('id', $id);
      $this->view->assign('List', $lclm->GetList());
      $this->view->assign($form->GetFrom());
      $this->view->xmlWriter->endElement();
      $this->view->xmlWriter->endElement();
      }

      public function downloadAction() {
      $id = intval($this->_request->getParam('id'));
      $attache_id = intval($this->_request->getParam('attache'));

      if (empty($id) || empty($attache_id)) $this->_redirect('/error/e404');

      $table_attaches = new Admin_Table_Auction_Attaches();
      $file_data = $table_attaches->getFileData($attache_id);

      if (empty($file_data)) $this->_redirect('/error/e404');

      $this->downloadAttachment($file_data['file_path'] . DIRECTORY_SEPARATOR . $file_data['file_name'], $file_data['name']);
      $this->_redirect("/" . $this->controller . "/file-attache/" . $id );
      }

      private function downloadAttachment($path, $name) {
      ignore_user_abort(true);
      set_time_limit(0);

      if (file_exists($path)) {
      if (preg_match('/Opera(\| )([0-9].[0-9]{1,2})/', $_SERVER['HTTP_USER_AGENT']))
      $UserBrowser = "Opera";
      elseif (preg_match('/MSIE ([0-9].[0-9]{1,2})/', $_SERVER['HTTP_USER_AGENT']))
      $UserBrowser = "IE";
      else
      $UserBrowser = "";

      $mime_type = ($UserBrowser == 'IE' || $UserBrowser == 'Opera') ? 'application/octetstream' : 'application/octet-stream';
      @ob_end_clean();

      header('Content-Type: ' . $mime_type);
      header('Content-Disposition: attachment; filename="' . $name . '"');
      header('Accept-Ranges: bytes');
      header("Cache-control: private");
      header('Pragma: private');
      header("Content-Length: " . filesize($path));

      $fd = fopen($path, "r");
      if ($fd) {
      while (!feof($fd)) {
      $buffer = fread($fd, 1024 * 128);
      echo $buffer;
      }
      @ob_flush();
      fclose($fd);
      }
      }
      }
     */

    public function ajaxDistrictsReloadAction() {
        $id_region = intval(@$_REQUEST['id_region']);

        echo "<option value='0'>-- Не вказано --</option>";

        if (is_numeric($id_region) && !empty($id_region)) {
            $items = $this->_table->addressGetDistricts($id_region);

            if (!empty($items) && is_array($items)) {
                foreach ($items as $value)
                    echo sprintf("<option value='%d'>%s</option>", $value['id'], $value['name']);
            }
        }

        die();
    }

    public function ajaxTownReloadAction() {

        $id_region = intval(@$_REQUEST['id_region']);
        $id_district = intval(@$_REQUEST['id_district']);

        echo "<option value='0'>-- Не вказано --</option>";

        if (is_numeric($id_region) && !empty($id_region) && is_numeric($id_district) && !empty($id_district)) {
            $items = $this->_table->addressGetTowns($id_region, $id_district);

            if (!empty($items) && is_array($items)) {
                foreach ($items as $value)
                    echo sprintf("<option value='%d'>%s</option>", $value['id'], $value['name']);
            }
        }
        die();
    }

}
